package com.wmwj.hxlj.service.impl;

import com.wmwj.hxlj.entity.CollectionFolder;
import com.wmwj.hxlj.entity.Follow;
import com.wmwj.hxlj.entity.User;
import com.wmwj.hxlj.entity.vo.*;
import com.wmwj.hxlj.mapper.CollectionFolderMapper;
import com.wmwj.hxlj.mapper.FollowerMapper;
import com.wmwj.hxlj.mapper.UserMapper;
import com.wmwj.hxlj.service.UserService;
import com.wmwj.hxlj.utils.BeanCopyUtils;
import com.wmwj.hxlj.utils.JWTUtils;
import com.wmwj.hxlj.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private FollowerMapper followerMapper;
    @Autowired
    private CollectionFolderMapper collectionFolderMapper;

    private static final Pattern PASSWORD_PATTERN = Pattern.compile(
            "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d|.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{6,16}$");
    private static final Pattern ACCOUNT_PATTERN = Pattern.compile("^[a-zA-Z0-9]{6,20}$");

    @Override
    public User findById(Long id) {
        return userMapper.findById(id);
    }

    @Override
    public Result<UserVo> register(User user) {
            // 1. 参数校验
            // 检查用户是否为空
            if (user == null || StringUtils.isEmpty(user.getAccount())) {
                return Result.error("用户信息不完整");
            }
            if(StringUtils.isEmpty(user.getPassword())){
                return Result.error("密码不能为空");
            }
            // 用户名格式
            // 检查用户名是否符合规定的格式
            if (!ACCOUNT_PATTERN.matcher(user.getAccount()).matches()) {
                return Result.error("用户名格式不正确，用户名长度在6到16个字符之间");
            }
            // 密码强度
            // 检查密码是否符合规定的强度
            if (!PASSWORD_PATTERN.matcher(user.getPassword()).matches()) {
                return Result.error("密码强度不够，密码必须包含大小写字母、数字或特殊字符，且长度在6到16个字符之间");
            }

            // 2. 检查用户名是否已存在
            // 检查数据库中是否已存在相同的用户名
            if (userMapper.findByAccount(user.getAccount()) != null) {
                return Result.error("用户名已存在");
            }

            // 3. 密码加密
            // 检查密码是否为空，如果不为空则进行加密
            if (StringUtils.hasText(user.getPassword())) {
                user.setPassword(encoder.encode(user.getPassword()));
            } else {
                return Result.error("密码不能为空");
            }

            // 设置默认用户类型
            // 如果用户类型为空，则设置为默认值
            if (StringUtils.isEmpty(user.getType())) {
                user.setType("0");
            }

            // 设置默认状态
            // 设置用户状态为默认值
            user.setStatus("0");
            // 设置默认头像
            // 如果用户头像为空，则设置为默认头像
            if (StringUtils.isEmpty(user.getAvatar())) {
                user.setAvatar("assets/img/avatar.png");
            }

            // 设置唯一id
            // 如果唯一ID为空，则生成一个新的唯一ID
            if(StringUtils.isEmpty(user.getUniqueId())){
                user.setUniqueId(UUID.randomUUID().toString());
            }

            // 设置默认创建时间
            // 如果创建时间为空，则设置为当前时间
            if (user.getCreateTime() == null) {
                user.setCreateTime(new Date());
            }

            // 设置默认更新时间
            // 如果更新时间为空，则设置为当前时间
            if (user.getUpdateTime() == null) {
                user.setUpdateTime(new Date());
            }

            // 设置默认删除标志
            // 如果删除标志为空，则设置为默认值
            if (user.getDelFlag() == null) {
                user.setDelFlag(0);
            }

            // 4. 执行插入操作
            // 将用户信息插入到数据库中
            int affectedRows = userMapper.insert(user);

            // 5. 验证插入结果
            // 如果插入的行数为0，则注册失败
            if (affectedRows == 0) {
                return Result.error("注册失败，请稍后重试");
            }

            //转换uservo对象返回对象
            UserVo userVo = BeanCopyUtils.copyBean(user, UserVo.class);
            User dbUser = userMapper.findById(user.getId());
            Map<String, Object> claims =new HashMap<>();
            claims.put("id", dbUser.getId());
            claims.put("account", dbUser.getAccount());

            userVo.setToken(JWTUtils.getToken(claims));

            return Result.success(userVo);

    }

    @Override
    public Result login(User user) {

        if (user == null || StringUtils.isEmpty(user.getAccount()) || StringUtils.isEmpty(user.getPassword())) {
            return Result.error("用户信息不完整");
        }
        User dbUser = userMapper.findByAccount(user.getAccount());
        if (dbUser == null) {
            return Result.error("用户不存在");
        }else if (encoder.matches(user.getPassword(), dbUser.getPassword())) {
            Map<String, Object> claims =new HashMap<>();
            claims.put("id", dbUser.getId());
            claims.put("account", dbUser.getAccount());

            String token = JWTUtils.getToken(claims);
            UserVo userVo = BeanCopyUtils.copyBean(dbUser, UserVo.class);
            userVo.setToken(token);
            //登录成功
            return Result.success( "登录成功",userVo);
        }else {
            return Result.error("密码错误");
        }



    }

    @Override
    public Result<String> updatePassword(Long id, String oldPassword, String newPassword) {
        // 1. 参数校验
        if (id == null || !StringUtils.hasText(oldPassword) || !StringUtils.hasText(newPassword)) {
            return Result.error("参数不完整");
        }

        // 2. 校验新密码格式
        if (!PASSWORD_PATTERN.matcher(newPassword).matches()) {
            return Result.error("新密码强度不够，密码必须包含大小写字母、数字或特殊字符，且长度在6到16个字符之间");
        }

        // 3. 获取用户信息
        User user = userMapper.findById(id);
        if (user == null) {
            return Result.error("用户不存在");
        }

        // 4. 验证旧密码
        if (!encoder.matches(oldPassword, user.getPassword())) {
            return Result.error("原密码错误");
        }

        // 5. 加密新密码
        String encryptedNewPassword = encoder.encode(newPassword);

        // 6. 更新密码
        int rows = userMapper.updatePassword(id, user.getPassword(), encryptedNewPassword, id.toString());
        if (rows > 0) {
            return Result.success("密码修改成功");
        } else {
            return Result.error("密码修改失败");
        }
    }

    @Override
    public Result<String> deactivateAccount(Long id, String password) {
        // 1. 参数校验
        if (id == null || !StringUtils.hasText(password)) {
            return Result.error("参数不完整");
        }

        // 2. 获取用户信息
        User user = userMapper.findById(id);
        if (user == null) {
            return Result.error("用户不存在");
        }

        // 3. 验证密码
        if (!encoder.matches(password, user.getPassword())) {
            return Result.error("密码错误");
        }

        // 4. 执行注销操作（软删除）
        int rows = userMapper.deleteById(id, id.toString());
        if (rows > 0) {
            return Result.success("账户注销成功");
        } else {
            return Result.error("账户注销失败");
        }
    }

    // 实现获取所有用户的方法
    @Override
    public Result<PageResult<AdminUserVo>> getAllUsers(Integer pageStart) {
        int pageStarts = (pageStart - 1) * 10;
        int pageSize = 10;
        try{
//            List<User> user = userMapper.findList(null);
            //获取用户列表
            List<User> user = userMapper.getUserList(pageStarts,pageSize);
            if(user == null){
                return Result.error("用户列表为空");
            }
            List<AdminUserVo> userVo = BeanCopyUtils.copyBeanList(user, AdminUserVo.class);
            //获取查询总记录数
            int total = userMapper.countUser();
            PageResult<AdminUserVo> pageResult = new PageResult<>(userVo,total);

            return Result.success(pageResult);
        }catch (Exception e){
            return Result.error("获取用户列表失败: " + e.getMessage());
        }
    }

    // 实现批量删除用户的方法
    @Override
    public Result<String> batchDeleteUsers(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return Result.error("用户ID列表不能为空");
        }

        try {
            for (Long id : ids) {
                User user = userMapper.findById(id);
                if (user == null) {
                    return Result.error("用户ID " + id + " 不存在");
                }
                // 执行软删除操作
                int rows = userMapper.deleteById(id, id.toString());
                if (rows <= 0) {
                    return Result.error("用户ID " + id + " 删除失败");
                }
            }
            return Result.success("批量删除用户成功");
        } catch (Exception e) {
            return Result.error("批量删除用户失败: " + e.getMessage());
        }
    }

    @Override
    public Result updateUserInfo(User user) {
        if (userMapper.findById(user.getId()) == null){
            return Result.error("用户不存在");
        }

        // 邮箱验证
        if (user.getEmail() != null && !user.getEmail().isEmpty()) {
            if (!user.getEmail().matches("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$")) {
                throw new RuntimeException("邮箱格式不正确");
            }
            if (userMapper.findByEmail(user.getEmail()) != null) {
                throw new RuntimeException("邮箱已存在");
            }
        }

        //手机号验证
        if (user.getPhoneNumber() != null && !user.getPhoneNumber().isEmpty()){
            if (!user.getPhoneNumber().matches("^1[3-9]\\d{9}$")){
                return Result.error("手机号格式不正确");
            }
        }

        int row = userMapper.updateUser(user);
        if (row > 0){
            UserVo userVo = BeanCopyUtils.copyBean(user, UserVo.class);
            return Result.success("更新用户信息成功", userVo);
        }

        else
            return Result.error("更新用户信息失败");
    }

    //支持模糊查询
    @Override
    public Result<List<UserVo>> searchUsersByAccount(String account) {
        List<User> users = userMapper.findByAccountLike(account);
        if (users.isEmpty()) {
            return Result.error("未找到相关用户");
        }

        List<UserVo> userVos = BeanCopyUtils.copyBeanList(users, UserVo.class);

        return Result.success(userVos);
    }

    /**
     * 关注用户
     * @param followee_id
     * @param follower_id
     * @return
     */
    @Override
    public Result<Integer> incrementFollowerCount(Long followee_id, Long follower_id) {
        if (followee_id == null || follower_id == null)
            throw new RuntimeException("参数不能为空");
        //用户不存在
        if(userMapper.findById(followee_id) == null || userMapper.findById(follower_id) == null)
            throw new RuntimeException("用户不存在");
        if(followee_id.equals(follower_id))
            throw new RuntimeException("不能关注自己");

        Follow follower = followerMapper.findByIdAndFollow(followee_id, follower_id);

        if(follower == null){
            followerMapper.insert(followee_id, follower_id);
            //粉丝数加一
            int row = userMapper.incrementFollowCount(followee_id);
            //关注数加一
            userMapper.incrementFollowerCount(follower_id);
            return Result.success("关注成功",row);
        }
        else if(follower.getStatus() == 0){
            //没有关注，添加关注状态
            int row = followerMapper.insertStatus(followee_id, follower_id);
            //粉丝数加一
            userMapper.incrementFollowCount(followee_id);
            //关注数加一
            userMapper.incrementFollowerCount(follower_id);
            return Result.success("关注成功",row);
        }else{
            //已经关注，取消关注
            int row = followerMapper.deleteStatus(followee_id, follower_id);
            //粉丝数减一
            userMapper.decrementFollowCount(followee_id);
            //关注数减一
            userMapper.decrementFollowerCount(follower_id);
            return Result.success("取消关注成功",-row);
        }
    }

    @Override
    public Result<Boolean> isFollowed(Long followeeId, Long followerId) {
        if (followeeId == null || followerId == null)
            throw new RuntimeException("参数不能为空");
        //用户不存在
        if(userMapper.findById(followeeId) == null || userMapper.findById(followerId) == null)
            throw new RuntimeException("用户不存在");
        if(followeeId.equals(followerId))
            throw new RuntimeException("不能关注自己");

        Follow follower = followerMapper.findByIdAndFollow(followeeId, followerId);
        if(follower == null){
            return Result.error(false);
        }
        else if(follower.getStatus() == 0){
            return Result.error(false);
        }else{
            return Result.success(true);
        }
    }

    @Override
    public Result<String> createCollectionFolder(CollectionFolder collectionFolder) {
        if(collectionFolder.getUserId() == null){
            throw new RuntimeException("用户不存在");
        }
        if(collectionFolder.getFolderName() == null || collectionFolder.getFolderName().isEmpty()){
            throw new RuntimeException("文件夹名称不能为空");
        }
        if(collectionFolderMapper.findByUserIdAndFolderName(collectionFolder.getUserId(), collectionFolder.getFolderName()) != null){
            throw new RuntimeException("文件夹已存在");
        }

        try {
            collectionFolderMapper.insert(collectionFolder);
            return Result.success("创建文件夹成功");
        }
        catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("创建文件夹失败");
        }

    }

    @Override
    public Result<List<CollectionFolderVo>> getCollectionFolder(Long userId) {
        if (userId == null && userMapper.findById(userId) == null){
            throw new RuntimeException("用户不存在");
        }
        List<CollectionFolder> collectionFolders = collectionFolderMapper.findByUserId(userId);
        if (collectionFolders.isEmpty()) {
            return Result.error("未找到相关文件夹");
        }

        List<CollectionFolderVo> collectionFolderVos = BeanCopyUtils.copyBeanList(collectionFolders, CollectionFolderVo.class);

        return Result.success(collectionFolderVos);
    }

    @Override
    public Result<String> batchDeleteCollectionFolder(Long userId,List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new RuntimeException("操作异常！");
        }
        if (userMapper.findById(userId) == null)
            throw new RuntimeException("用户不存在");

        //身份验证
        for (Long id : ids) {
            if (collectionFolderMapper.findById(id) == null)
                throw new RuntimeException("文件夹不存在");
            if (collectionFolderMapper.findById(id).getUserId() != userId)
                throw new RuntimeException("文件夹不属于该用户");
        }

        try {
            //批量删除文件夹
            collectionFolderMapper.deleteByIds(ids);
            return Result.success("删除文件夹成功");
        }
        catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("删除文件夹失败");
        }
   }

   @Override
    public Result<CollectionFolder> updateCollectionFolder(CollectionFolder collectionFolder) {
        if (collectionFolder.getId() == null)
            throw new RuntimeException("参数不存在");
        if (collectionFolderMapper.findById(collectionFolder.getId()) == null)
            throw new RuntimeException("文件夹不存在");

        try {
            collectionFolderMapper.update(collectionFolder);
            return Result.success("修改文件夹成功", collectionFolder);
        }
        catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("修改文件夹失败");
        }
    }

    @Override
    public Result<String> deleteUser(Long id) {
        if (id == null)
            throw new RuntimeException("参数不能为空");

        if (userMapper.findById(id) == null)
            throw new RuntimeException("用户不存在");

        try {
            userMapper.adminDeleteById(id);
            return Result.success("删除用户成功");
        }
        catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("删除用户失败");
        }

    }

    @Override
    public Result<PageResult<AdminUserVo>> adminSearchUsersByAccount(String account, Integer pageStart) {
        if (account == null || account.isEmpty())
            throw new RuntimeException("参数不能为空");
        if (pageStart == null)
            throw new RuntimeException("参数不能为空");
        int pageStarts = (pageStart -1) * 10;
        int pageSize = 10;

        List<User> users = userMapper.adminSearchUsersByAccount(account, pageStarts, pageSize);

        if (users == null || users.isEmpty()) {
            return Result.error("没有找到相关用户");
        }

        List<AdminUserVo> adminUserVos = BeanCopyUtils.copyBeanList(users, AdminUserVo.class);

        PageResult<AdminUserVo> pageResult = new PageResult<>(adminUserVos, userMapper.adminCountByKeyword(account));

        return Result.success(pageResult);
    }

}
